<template>
  <ul>
    <li><div @click="logOp">点我打印操作符</div></li>
    <li
      v-for="(item, index) in operators"
      :key="index"
      class="orerator-list-li"
    >
      <yzOperator
        :model="item"
        :labelOptions="labelOptions"
        style="width: 80%"
      ></yzOperator>
      <div @click="addOp">添加</div>
      <div @click="removeOp(item)">移除</div>
    </li>
  </ul>
</template>
<script>
import yzOperator from './yz-operator.vue'
import YzOperator from 'src/boot/common/yzOperator'
import YzOperand from 'src/boot/common/yzOperand'
export default {
  props: {
    model: {
      type: YzOperator,
      require: true
    },
    labelOptions: {
      type: Array,
      require: true
    }
  },
  emit: ['updateRoot'],
  components: {
    yzOperator
  },
  model: {
    prop: 'model',
    event: 'submit'
  },
  computed: {
    operators () {
      return this.getBasicOperators()
    }
  },
  methods: {
    getBasicOperators () {
      if (!this.model) {
        return []
      }
      let allOp = this.model.getAllOperators()
      return allOp.filter(op => YzOperator.getBasicOperator().includes(op.op))
    },
    addOp () {
      // 添加就是 &&
      let targetOperator = new YzOperator(new YzOperand('variable'), '==', new YzOperand('real'))
      let basicOperators = this.getBasicOperators()
      let index = basicOperators.indexOf(this.model)
      let targetOps = basicOperators.splice(index, 0, targetOperator)
      let finalOp = targetOps[0]
      for (let index = 1; index < targetOps.length; index++) {
        const target = targetOps[index]
        finalOp = this.constructAndOp(finalOp, target)
      }
      this.$emit('updateRoot', finalOp)
    },
    removeOp (op) {
      let basicOperators = this.getBasicOperators()
      let targetOps = basicOperators.filter(o => o !== op)
      let finalOp = targetOps[0]
      for (let index = 1; index < targetOps.length; index++) {
        const target = targetOps[index]
        finalOp = this.constructAndOp(finalOp, target)
      }
      this.$emit('updateRoot', finalOp)
    },
    // 构造与符号操作符
    constructAndOp (sourceOp, targetOp) {
      return new YzOperator(new YzOperand('op', sourceOp), '&&', new YzOperand('op', targetOp))
    },
    logOp () {
      console.log(this.model)
      console.log(JSON.stringify(this.model))
      console.log(this.model.getDisplayString())
      console.log(this.model.getExecJsString())
    }
  }
}
</script>

<style lang="scss">
.orerator-list-li {
  display: flex;
  border: solid 1px;
}
</style>
